var util=require('../../utils/util.js');
var cartjs=require('../../utils/shopcat.js');
var foodcart=require('../../utils/foodcart.js')
var voice=require('../../utils/voiceorder.js');
var payjs=require('../../utils/pay.js');
Page({
  data: {
    block: false,
    restaurant: false,
    check: true,


    time2arr: [['现在', '今天'/*, '明天'*/],[1,2,3,4,5,6,7,8,9,10],['00','05','10','15','20']],
    time2index:[0,0,0],
    future:false,

    weiuser: { },
    cartlist: [
      /**{ id: 2, pic: "../../img/food2.jpg", name: "五花肉石锅拌饭", num: "2", price: 51, oprice: 20, idt: "配米饭一份哦",  },
               { id: 2, pic: "../../img/food2.jpg", name: "五花肉石锅拌饭", num: "4", price: 51, oprice: 20, idt: "配米饭一份哦",  taste:  "姜葱味" }*/],
    amount:0,
    discount:0,
    payamount:0,
    order:{},
    online:false, 
    inSubmit:false,  
    
    voiceremark:'',

    inVoiceShow:'',

    redpackage:{},
    //外卖

    wayAmount:0,
    userAddress:{},
    dinType: [{ id: 0, name: '堂食',checked:true }, { id: 1, name: '自取' }, { id: 2, name: '外卖' }],
    dining:0,
    dinTime:['就餐时间','取餐时间','送餐时间'],
    distance:0,
    indistance:true,

  },
  onLoad:function(options){
    
    var oid=options.oid;
    this.setData({ imghost: getApp().globalData.imghost});
    var date=new Date();
    var hour=date.getHours();
    if (hour<10){hour="0"+hour}
    var minutes=date.getMinutes();
    if (minutes<10){minutes="0"+minutes}
    var time2arr = [['现在','今天'/*,'明天'*/], [hour], [minutes]];
    this.setData({
      time2arr: time2arr ,      
    }); 
    var weiuser = wx.getStorageSync('weiuser');
    this.setData({
      weiuser: weiuser,
      shopinfo:wx.getStorageSync("shopinfo")
    })
    if (oid>0){
      this.anotherOrder(oid);
    }else{
      var ret = foodcart.getFoodlist();
      this.setData({
        cartlist: ret.foodlist,
        amount: ret.buycart.buyamount,
        payamount: ret.buycart.buyamount,
      });
      
      var voiceremark = wx.getStorageSync("voiceremark");
      if (voiceremark && voiceremark != '') {
        this.setData({ 'order.remark': voiceremark })
      }
    }
    
  },


  onShow:function(){
    this.getOrderAmount();
  },
  
  anotherOrder:function(oid){
    var that = this;
    var url = util.url.order_copy;
    url += "?id=" + oid;
    util.fetchGet(
      url,
      function (data) {
        var suborders = data.data;
        var carts = [];
        var tnum = 0,tamount=0;
        var foodlist=wx.getStorageSync("foodlist");
        for (var j = 0; j < foodlist.length; j++) {
          foodlist[j].selected=false;
          for (var i = 0; i < suborders.length; i++) {         
            if (foodlist[j].id == suborders[i].id){
              foodlist[j].selected=true;
              foodlist[j].num = suborders[i].num;
              tnum += foodlist[j].num;
              tamount += Number(foodlist[j].num) * Number(foodlist[j].price);
            }
          }
        
        }
        that.setData({
          cartlist: foodlist,
          amount: tamount,
          payamount: tamount,          
        });
      }
    )
  },

  bindTimeHourChange:function(e){ 
    var hourindex = e.detail.value;
    console.log("hourindex：" + hourindex);
    this.setData({
      time2index: hourindex,
       
    })
    
  },
  bindTimeMinutesChange:function(e){
    var minutesindex=e.detail.value;
  //  console.log("minutesindex:" + minutesindex)
 //   console.log("minutescolumn:" + e.detail.column)
    if (e.detail.column ==0){
      var time2arr = this.data.time2arr;
      if (minutesindex == 1) {
        var date = new Date();
        var hour = date.getHours();
        var minutes = date.getMinutes();
        var arr1=[];
        
        for (var i = hour+1;i<24;i++){
          arr1.push(i);
        }
        time2arr[1] = arr1;
        time2arr[2] = ['00',  '10', '20',  '30',  '40',  '50'];
      } else if (minutesindex == 2) {
        time2arr[1] = ['00', '01', '02','03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
        time2arr[2] = ['00', '10', '20', '30', '40', '50'];
      } else if (minutesindex==0){
        var date = new Date();
        var hour = date.getHours();
        var minutes = date.getMinutes();
        time2arr = [['现在', '今天'/*, '明天'*/], [hour], [minutes]];
      }
      this.setData({
        time2arr: time2arr
      })
    }
    
  },
  calling: function() {
    var shopinfo = wx.getStorageSync("shopinfo");
    wx.makePhoneCall({
      phoneNumber: shopinfo.phone, 
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    }) 
  },
  bindReMarkIn:function(e){
    this.setData({
      'order.remark':e.detail.value
    })
  },
  
  createOrder:function(){
    if (this.data.inSubmit){
      console.log("已经提交，请等待！");return ;
    }
    var shopinfo=wx.getStorageSync("shopinfo");
    var that =  this;
    var order=that.data.order;
    var time2arr = that.data.time2arr;
    var time2index=that.data.time2index;
    var cartlist = that.data.cartlist;
    var suborder=[]
    var cartnew=[];
    var bagnum=0;
    for(var i=0;i<cartlist.length;i++){
      if (cartlist[i].selected && cartlist[i].num>0){
        suborder.push(cartlist[i]);
      }else{
        cartnew.push(cartlist[i]);
        bagnum += cartlist[i].num;
      }
    }
    order.fetchtime= time2arr[0][time2index[0]] + ',' + time2arr[1][time2index[1]] + ':' + time2arr[2][time2index[2]]
    order.paytype=0;
    order.dining=this.data.dining;
    if (order.dining==2){
      order.userAddress = this.data.userAddress;
      order.wayAmount = this.data.wayAmount;
      var indistance = this.data.indistance;
      if (!indistance){
        util.showinfo("不在配送范围，请添加修改配送地址");
        return;
      }
    }
    
    order.suborder = suborder;
    order.shop = shopinfo.id;
    var redpackage = this.data.redpackage;
    if (redpackage && redpackage.id){
      
      order.redpackage = redpackage.id
    }else{
      order.redpackage = 0;
    }
    
    util.fetchPost(
      util.url.order_create,
      order,
      function(ret){
        that.setData({
          "order.id":ret.data.order.id
        })
        that.initorder(cartnew, bagnum);
        payjs.createPay(ret.data.payment,function(succ,ret){
          if (succ){
            util.showinfo("支付成功")
          }else{
            util.showinfo("支付失败，请重试")
          }
        })
        
      }
    )
  },
  preOrder:function(){
    var that = this;
    var order = {};
    if (that.data.dining != 2) {
      return ;
    }
    var shopinfo = wx.getStorageSync("shopinfo");
    var suborder = []
    var cartlist = that.data.cartlist;
    for (var i = 0; i < cartlist.length; i++) {
      if (cartlist[i].selected && cartlist[i].num > 0) {
        suborder.push(cartlist[i]);
      }
    }
    order.dining = that.data.dining;;
    order.suborder = suborder;
    order.shop = shopinfo.id;
    //if (order.dining == 2) {
    order.userAddress = that.data.userAddress;     
    //}
    util.fetchPost(
      util.url.user_delivery_preorder,
      order,
      function (ret) {
        console.log(ret);
      }
    )
  },
  initorder: function (cartnew, bagnum){
    util.setTabBadge(1, bagnum);
    foodcart.initFoodList()//去除购物车中选中的物品
    wx.setStorageSync("redpackage", null);// 去除选中的卡券
    wx.setStorageSync("voiceremark", "");//去除首页输入的语音备注
  },
  

  toMyPackage:function(){
    var amount=this.data.amount;
    wx.navigateTo({
      url: '../myPackage/myPackage?amount=' + amount,
    })
  },
  startVoice:function(){
    var that=this;
    that.setData({
      inVoiceShow: '正在录音识别...'
    })
    voice.startVoice(
      function(succ,text,file){
        if (succ){
          that.setData({ 'order.remark': text, inVoiceShow:''});
        }else{
          that.setData({ inVoiceShow:'录音识别失败...' });
        }
      }
    )
  },
  stopVoice:function(){
    var that=this;
    voice.stopVoice(function(){
      that.setData({
        inVoiceShow:''
      })
    })
  },
  toMyAddress:function(){
    wx.navigateTo({
      url: '/pages/address/address',
    })
  },
 
  binddiningType:function(e){
    var value=e.detail.value;
    this.setData({
      dining:value
    })
    if (value==2){
      this.getDefaultAddress();
    }
    this.getOrderAmount();
  },
  getDefaultAddress:function(){
      
    var userAddress=this.data.userAddress;
    if (userAddress && userAddress.id){
      return ;
    }
    var that=this;
    var url = util.url.user_address_getdefault;
    util.fetchGet(
      url,
      function(ret){
        var address=ret.data;
        if (address && address.id){
          that.setUserAddress(address);
        }
      }
    )
  },
  getWayAmount:function(){
    var that=this;
    var wayAmount=550;
  //预下外卖单  获取配送费
   // this.preOrder(); 
    that.getWayAmountFromBack(function(){
      that.getOrderAmount()
    });

    
  },
  getWayAmountFromBack:function(callback){
    var that=this;
    var url = util.url.user_delivery_getwaycost;
    var data={};
    var userAddress = this.data.userAddress.address.location;
    var shopAddress = this.data.shopinfo.address.location;
    data = { user: userAddress,shop:shopAddress}
    util.fetchPost(  
      url,
      data,
      function(ret){
          that.setData({
            indistance:true,
            wayAmount: ret.data.estcost,
            distance: ret.data.distance
          })  
          if (callback){
            callback();
          }             
      },
      function(error){
        that.setData({
          indistance: false,
        })
      }

    )
  },

  getOrderAmount:function(){
    var dining = this.data.dining;
    var amount=this.data.amount;
    var disamount=this.getRedDisAmount();
    var payamount = amount - disamount;
    
    if (dining==2){
      payamount += this.data.wayAmount;
    }
    this.setData({
      discount:disamount,
      payamount: payamount
    }) 
  },
  getRedDisAmount:function(){
    var redpackage = this.data.redpackage;
    if (redpackage) {
      var dis = 0;
      var amount = this.data.amount
      if (redpackage.redtype == 0) {
        var discount = redpackage.discount;
        if (discount && discount != 0) {
          dis = (100 - discount) / 100 * amount;
        }
      } else if (redpackage.redtype == 1) {
        var reduction = redpackage.reduction;
        reduction.sort(function (a, b) {
          return b.full - a.full;
        })
        for (var i = reduction.length - 1; i >= 0; i--) {
          if (amount >= reduction[i].full * 100) {
            dis = reduction[i].reduce * 100;
            break;
          }
        }

      }
      dis = dis.toFixed(0);
      return dis;
    }
    return 0;
  },
  
   setUserAddress:function(address){
     this.setData({
       userAddress:address
     })
     this.getWayAmount();
   } 
})